import streamlit as st
from tools.SecureCookieManager import SecureCookieManager
from scripts.vpShere_manager import VsphereManager
from tools.DBUtil import DBUtil
import pandas as pd

st.title("云虚拟机管理")
##########################################################获取页面所需要的数据##################################################################
# 获取待创建和已创建的虚拟机列表数据，并缓存到session_state中
if 'created_data' not in st.session_state or 'waiting_data' not in st.session_state:
    st.session_state.created_data = []
    st.session_state.waiting_data = []
    cookie_manager = SecureCookieManager()
    current_username = cookie_manager.get_cookie("username")
    if current_username=="admin":
        st.session_state.created_data  = DBUtil.select_all("SELECT id, vmname, function, applytime, applyreason, endtime FROM vm_list;")
        st.session_state.waiting_data = DBUtil.select_all("SELECT vmname, applytime FROM vm_apply_his WHERE approvalstatus = 0;")  # 显示等待审批的申请
    else:
        st.session_state.created_data = DBUtil.select_all("SELECT vm_list.id, vmname, function, applytime, applyreason, endtime FROM vm_list,user WHERE owner_id=user.id and username=%s;",(current_username,))
        st.session_state.waiting_data = DBUtil.select_all("SELECT vmname, applytime FROM vm_apply_his where username=%s and approvalstatus = 0;",(current_username,))  # 显示用户自己的虚拟机列表

# 获取可选的虚拟机选项，并缓存到session_state中
if 'server_options' not in st.session_state:
    st.session_state.server_options = [""]
    for i in st.session_state.created_data:
        st.session_state.server_options.append(i['vmname'])

# 获取可选的用户选项,并缓存到session_state中
if 'user_options' not in st.session_state:
    st.session_state.user_options = [""]
    st.session_state.vspheremanager =None

    st.session_state.vspheremanager = VsphereManager("10.1.109.100","yfzxxtb@vsphere.local","Qqqq@12345678","Datacenter","虚拟机模板/202409")
    if st.session_state.vspheremanager.connect():
       st.session_state.user_options = st.session_state.vspheremanager.get_user_list()
##########################################################待创建的虚拟机列表##################################################################
# 标题
st.subheader("一、已申请待创建的虚拟机列表")
# 显示等待审批的申请
if st.session_state.waiting_data:
    df = pd.DataFrame(st.session_state.waiting_data)
    df.columns = ['虚拟机名称', '申请时间']
    df.set_index('虚拟机名称', inplace=True)
    st.dataframe(df)  # 显示虚拟机列表
else:
    st.warning("暂无数据")


##########################################################已创建的虚拟机列表##################################################################
# 标题
st.subheader("二、已创建的虚拟机列表")
# 添加权限

with st.form("add_permission_form",border=False):
    col1,col2,col3 = st.columns(3)
    server_name = col1.selectbox("选择需要添加权限的虚拟机", st.session_state.server_options, index=0)
    users_list = col2.multiselect("选择需要添加权限的用户", st.session_state.user_options, placeholder="")
    col3.markdown("<p style='height:12px;'></p>", unsafe_allow_html=True)
    add_permission_button = col3.form_submit_button("添加权限")

message = st.empty()
if add_permission_button:
    if server_name and users_list:
        try:
            message.info(f"正在查找虚拟机对象并添加权限到 {server_name}...")
            st.session_state.vspheremanager.add_permission_to_vm(server_name,"sznari.com",users_list,-2089829018)
            message.success("添加虚拟机权限成功!")

        except Exception as e:
            message.error(e)  
    else:
        message.warning("请选择需要添加权限的虚拟机和用户")

# 显示已创建的虚拟机列表
if st.session_state.created_data:
    df2 = pd.DataFrame(st.session_state.created_data)
    df2.columns = ['序号','虚拟机名称', '功能', '申请时间', '申请原因', '结束时间']
    df2.set_index('序号', inplace=True)
    st.dataframe(df2)  # 显示虚拟机列表
else:
    st.warning("暂无数据")